<?php
/**
 * Account_Controller_Admin
 *  
 * Controller for actions (in admin area) of admin module
 *
 * @version 2012-10-10
 * @package account
 * @subpackage controller
 * @category Account_Controller_Admin
 */

/**
 * Include common class (in all areas)
 */
require_once("global.php");

class Account_Controller_Admin extends Account_Controller_Global
{
	/** 
	* Index
	* Default function that will be used upon module start-up.
    *
    * @version 2012-10-10
    * @param Request $req
    * @return view
    * @access public
    */
    public function processIndex($req)
    {
		if(!$_SESSION['admin']['id']) {
			$this->processLogin($req);
		}
		else {
			$url = new Url();
            $url->clearParams();
        	$url->setParam('mod','admin');
            $req->forward($url->getUrl());
		}	
    }

    /**
    * Login
    * This function shows admin login form.
	* This function checks whether the "Remember Login" checkbox is checked. If true, login email will be inserted from cookies.
	* 
    * @param Request $req
    * @return View (login page)
    * @access public
    */
    public function processLogin($req)
    {
		// Here local values are declared 	
    	$layout = new View('tpl/layout_admin_login');
		$data = $req->getArray('data');
		$data['you_blocked'] = $req->getArray('you_blocked');
        $layout->setVar('data', $data);
		$layout->setVar('errors', $this->getErrors());
		
	    echo $layout->fetch();
	    exit();
    }


    /**
    * DoLogin
    * This function checks email and password in the database. If login and password coincide with those recorded in the database, a redirect to admin panel is performed.
    * 
    * @param Request $req
    * @return View or 
    * @access public
    */
    public function processDoLogin($req)
    {
		$data = $req->getArray('data');
		
        $dbAccounts = Db::getModel("member_accounts");
        $result = $dbAccounts->findBy(array("login_key"=>"='".$data['login']."'","utype"=>"='admin'"),array(),0,1);
        if(empty($data['login']) or empty($data['password'])){
            return $this->processLogin($req);
        }
        elseif($result[0]){
           if($result[0]['blocked'] <= 0){
            $this->addErrors(_fmt('account.blocked')); 
            return $this->processLogin($req);
           } elseif(_pass($data['password']) == $result[0]['password_key']){
               $_SESSION[$result[0]['utype']] = array(
                    "id" => $result[0]['uuid'],
					'login' => $result[0]['login_key'],
					'last_visit' => $result[0]['last_visit']
                 );
               $dbAccounts->update(array('last_visit'=> _dformat(time(),_cfg('format.datetime.sql')),'blocked'=>3), $result[0]['uuid']);
               $req->forward("/admin/");
           }
           else {
                $dbAccounts->update(array("blocked"=>($result[0]['blocked'] - 1)),$result[0]['uuid']);
                $this->addErrors(_fmt('account.login.error')); 
                return $this->processLogin($req);
           }
        }else{
            $this->addErrors(_fmt('account.login.error')); 
            return $this->processLogin($req);
        }
        exit;
    }

	/**
    * GetUnblockedEmail
    * This function send email unblocked link.
    *
    * @version 2012-10-14
    * @param Request $req
    * @return View (login page)
    * @access public
    */
    public function processGetUnblockedEmail($req)
    {
        $fields['data[email]'] = array('title'=>'Email', 'def' => 'email');
        $val = new Validator($fields); 
  
        if(!$val->isValid($req->getArgs())){
			$url = new Url();
			$url->clearParams();
			$url->setParam('mod','account');
			$url->setParam('act','login');
			$url->setParam('you_blocked','yes');
			$req->forward($url->getUrl(),null, $val->getErrors());  
        }else{
			$url = new Url();
			$url->clearParams();
			$url->setParam('mod','account');
			$url->setParam('act','login');
            $req->forward($url->getUrl(),_fmt('email.umblocked.link'));
        }
        exit;
    } 

    /** 
    * Logout
    * This function logs out an admin user and removes "admin" session.
    * 
    * @param Request $req
    * @return redirect (admin login page)
    * @access public
    */
    public function processLogout($req)	
	{
		unset($_SESSION['admin']);
		$req->forward("/admin/");
	}     
}